package common.helper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;

/**
 * Created by zhuxh on 16/7/26.
 */
public class OffsetLimitResultSetExtractor implements ResultSetExtractor {

  private int limit;
  private int offset;
  private RowMapper rowMapper;

  public OffsetLimitResultSetExtractor(int offset, int limit, RowMapper rowMapper) {
    Assert.notNull(rowMapper, "\'rowMapper\' must be not null");
    this.rowMapper = rowMapper;
    this.offset = offset;
    this.limit = limit;
  }

  @Override
  public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
    ArrayList results = new ArrayList(this.limit > 50 ? 50 : this.limit);
    if (this.offset > 0) {
      rs.absolute(this.offset);
    }

    int rowNum = 0;

    while (rs.next()) {
      Object row = this.rowMapper.mapRow(rs, rowNum++);
      results.add(row);
      if (rowNum + 1 >= this.limit) {
        break;
      }
    }

    return results;
  }
}
